<template>
  <div class="app-container">
    <div class="search-container">
      <el-form inline label-width="68px" ref="queryFromRef" :model="queryParams">
        <el-form-item label="通知类型">
          <el-select placeholder="通知类型" v-model="queryParams.noticeType">
            <el-option label="全部" value="" />
            <el-option label="公告" value="1" />
            <el-option label="会议" value="2" />
            <el-option label="其他" value="99" />
          </el-select>
        </el-form-item>
        <el-form-item label="标题">
          <el-input v-model="queryParams.title" placeholder="" />
        </el-form-item>
        <el-form-item label="通知时间">
          <el-date-picker
            :editable="false"
            class="!w-[240px]"
            v-model="queryParams.createTimeArr"
            type="daterange"
            range-separator="~"
            start-placeholder="开始时间"
            end-placeholder="截止时间"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item>
          <el-button class="filter-item" type="primary" @click="handleQuery">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="handleResetQuery"> <i-ep-refresh />重置 </el-button>
          <el-button v-hasPerm="['sys:notice:add']" type="success" @click.stop="handleOpenDialog()">
            <i-ep-plus />
            新增
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <el-table v-loading="loading" stripe :data="list" style="width: 100%">
        <el-table-column label="ID" width="50" prop="id" />
        <el-table-column label="标题" width="300" prop="title" />
        <el-table-column label="通知类型" width="100" prop="noticeType">
          <template #default="scope">
            <el-tag v-if="scope.row.noticeType === '1'" size="small" type="success">公告</el-tag>
            <el-tag v-else-if="scope.row.noticeType === '2'" size="small" type="info">会议</el-tag>
            <el-tag v-else size="small" type="warning">其他</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="发送者" width="100" prop="createBy" />
        <el-table-column label="是否发送" width="100" prop="sendFlag">
          <template #default="scope">
            <el-tag v-if="scope.row.sendFlag" type="success">已发送</el-tag>
            <el-tag v-else type="info">未发送</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="修改时间" width="200" prop="updateTime" />

        <el-table-column fixed="right" label="操作" width="240">
          <template #default="scope">
            <el-button
              v-hasPerm="['sys:post:delete']"
              type="primary"
              link
              size="small"
              @click.stop="handleOpenDialog(scope.row.id)"
            >
              <i-ep-edit />
              修改
            </el-button>
            <el-button
              v-hasPerm="['sys:notice:send']"
              type="primary"
              link
              size="small"
              @click.stop="handleSend(scope.row.id)"
            >
              <i-ep-message />
              发送
            </el-button>
            <el-button
              v-hasPerm="['sys:notice:delete']"
              type="danger"
              link
              size="small"
              @click.stop="handleDelete(scope.row.id)"
            >
              <i-ep-delete />
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <el-drawer v-model="dialog.visible" :title="dialog.title" @close="handleCloseDialog" size="50%">
      <el-form ref="addFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="通知类型" prop="noticeType">
          <el-select v-model="formData.noticeType" placeholder="请选择通知类型">
            <el-option label="公告" value="1" />
            <el-option label="会议" value="2" />
            <el-option label="其他" value="99" />
          </el-select>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入标题" />
        </el-form-item>

        <el-form-item label="内容" prop="content">
          <el-input
            v-model="formData.content"
            type="textarea"
            :rows="10"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="是否全部机构" prop="sendAllDept">
          <el-switch v-model="formData.sendAllDept" />
        </el-form-item>

        <el-form-item label="发送机构" prop="deptIds" v-show="!formData.sendAllDept">
          <el-tree-select
            v-model="formData.deptIds"
            placeholder="选择机构ID"
            :data="deptTreeOptions"
            filterable
            show-checkbox
            multiple
            check-strictly
            :render-after-expand="false"
          />
        </el-form-item>

        <el-form-item label="备注">
          <el-input v-model="formData.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
defineOptions({
  name: 'Notice',
  inheritAttrs: false
})

import { ElForm, ElTable } from 'element-plus'
import { ref, reactive, onMounted } from 'vue'
import request from '@/utils/request'
const BASE_URL = '/api/yyplatform/admin/sys/notice/'

const list = ref([])
const total = ref(0)
const loading = ref(false)
const deptTreeOptions = ref()

const addFormRef = ref(ElForm)
const formData = ref({
  id: '',
  title: '',
  content: '',
  noticeType: '',
  remark: '',
  sendAllDept: false,
  deptIds: []
})
const queryFromRef = ref()
const dialog = ref({
  title: '',
  visible: false
})
const rules = ref({
  title: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
  content: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
  noticeType: [{ required: true, message: '必填项不能为空', trigger: 'blur' }]
})
const queryParams = ref({
  title: '',
  noticeType: '',
  pageNum: 1,
  pageSize: 20,
  deleteFlag: false,
  createTimeArr: []
})

async function loadDeptTree() {
  let res = await request({
    url: `/api/yyplatform/admin/sys/dept/options`,
    method: 'get'
  })
  console.log('res=>', res)

  deptTreeOptions.value = [{ value: '0', label: '顶级机构', children: res }]
}

function handleCloseDialog() {
  dialog.value.visible = false
  dialog.value.title = '添加通知'
  formData.value = {
    id: '',
    title: '',
    content: '',
    noticeType: '',
    remark: '',
    sendAllDept: true,
    deptIds: []
  }
}
async function handleOpenDialog(id) {
  if (id) {
    let res = await request({
      url: `${BASE_URL}/get?id=${id}`,
      method: 'get'
    })
    formData.value = res
    dialog.value.visible = true
    dialog.value.title = '修改通知'
  } else {
    dialog.value.visible = true
    dialog.value.title = '添加通知'
    formData.value = {
      id: '',
      title: '',
      content: '',
      noticeType: '',
      remark: '',
      sendAllDept: true,
      deptIds: []
    }
  }
}
async function submitForm() {
  addFormRef.value.validate(async (isValid) => {
    if (isValid) {
      const id = formData.value.id
      if (id) {
        let updateRes = await request({
          url: `${BASE_URL}/update`,
          method: 'post',
          data: formData.value
        })
        ElMessage.success('修改成功')
        handleCloseDialog()
        await handleQuery()
      } else {
        let addRes = await request({
          url: `${BASE_URL}/save`,
          method: 'post',
          data: formData.value
        })
        ElMessage.success('添加成功')
        handleCloseDialog()
        await handleQuery()
      }
    }
  })
}

// ================================= 删除 =================================
function handleDelete(id) {
  ElMessageBox.confirm('确认删除已选中的数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    request({
      url: `${BASE_URL}/delete`,
      method: 'post',
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      data: {
        id: id
      }
    }).then(async () => {
      await handleQuery()
    })
  })
}

function handleSend(id) {
  ElMessageBox.confirm('确认发送已选中的数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    request({
      url: `${BASE_URL}/send`,
      method: 'post',
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      data: {
        id: id
      }
    }).then(async () => {
      await handleQuery()
    })
  })
}

// ================================= 分页查询 =================================
async function handleResetQuery() {
  await handleQuery()
}

async function handleQuery() {
  console.log(queryParams.value, 'queryParams')

  loading.value = true

  let queryRes = await request({
    url: `${BASE_URL}/query`,
    method: 'get',
    params: {
      ...queryParams.value
    }
  })

  loading.value = false
  list.value = queryRes.content
  total.value = parseInt(queryRes.totalElements)
}

onMounted(async () => {
  await handleQuery()
  await loadDeptTree()
})
</script>
